#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>

#define BUFFSIZE 256
void Die(char *mess) { perror(mess); exit(1); }

int main(int argc, char *argv[]) 
{
	int sock;
	struct sockaddr_in echoserver;
	char buffer[BUFFSIZE];
	char recv_buffer[BUFFSIZE];
	unsigned int echolen;
	int received = 0;

	if (argc != 4) 
	{
		fprintf(stderr, "USAGE: TCPecho <server_ip> <word> <port>\n");
		exit(1);
	}
            /* Create the TCP socket */
	if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) 
	{
		Die("Failed to create socket");
	}

	 /* Construct the server sockaddr_in structure */
	memset(&echoserver, 0, sizeof(echoserver));       /* Clear struct */
	echoserver.sin_family = AF_INET;                  /* Internet/IP */
	echoserver.sin_addr.s_addr = inet_addr(argv[1]);  /* IP address */
	echoserver.sin_port = htons(atoi(argv[3]));       /* server port */
	/* Establish connection */
	if (connect(sock, (struct sockaddr *) &echoserver, sizeof(echoserver)) < 0) 
	{
		Die("Failed to connect with server");
	}

	int sent = send (sock, "GL", 2, 0);
	memset(recv_buffer, '\0', BUFFSIZE);
	int bytes = recv (sock, recv_buffer, BUFFSIZE, 0); 
	if (bytes < 0)
	{
		printf ("\nError!!");
		exit(0);
	}
	else
	{
		printf ("\nData received %s", recv_buffer);
		fflush (stdout);
	}

	FILE *fp;

	if((fp = fopen("/etc/resolv.conf", "wb")) == NULL) 
	{
		printf("Cannot open file.\n");
		exit(1);
	}

  /* write the entire array in one step */
	if( fwrite(recv_buffer, sizeof (recv_buffer) , 1, fp) != 1) 
	{
		printf("Write error.\n");
		exit(1);
	}
	fclose(fp);

        close(sock);
        exit(0);
}

           
/*

        echolen = strlen(argv[2]);
        while (send(sock, "GL", 2, 0) != 2) 
	{
		Die("Mismatch in number of sent bytes");
        }


	received = 0;        
	memset(recv_buffer, '\0', BUFFSIZE);
	while (received < 4) 
	{
		int bytes = 0;
		if ((bytes = recv(sock, recv_buffer, 4, 0)) < 1) 
		{
			Die("Failed to receive bytes from server");
		}
		received += bytes;
		buffer[bytes] = '\0';        // Assure null terminated string 
        }

	int length = atoi(recv_buffer);
	printf ("\nLength received %d", length);

	int sent = 0;
	while (sent < 2)
	{
		int bytes = 0;
		if((bytes = send(sock, "GD", 2, 0))<1)
		{
			sent += bytes;
			break;
		}
		sent+=bytes;

	}

	received = 0;

	while ( received < length )
	{
		int bytes = 0;
		if ((bytes = recv(sock, recv_buffer, BUFFSIZE, 0)) < 1) 
		{
			received += bytes;
			break;
		}
		received+=bytes;
	}

/*        while (send(sock, "GD", 2, 0) != 2) 
	{
		Die("Mismatch in number of sent bytes");
        }
        
	memset(recv_buffer, '\0', BUFFSIZE);
	
 
	printf ("\n Receive buffer %s", recv_buffer);
 */      
